package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author anshuai
 * @create 2021-02-04 19:47
 */
@Service
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 添加好友
     *
     * @param userId1 用户1的id
     * @param userId2 用户2的id
     */
    @Override
    public void addFriend(Long userId1, Long userId2) {
        //1. 给userId1添加好友：userId2
        boolean exists = mongoTemplate.exists(new Query(Criteria.where("userId").is(userId1).and("friendId").is(userId2)), Friend.class);

        if (!exists) {
            Friend friend = new Friend();
            friend.setCreated(System.currentTimeMillis());
            friend.setFriendId(userId2);
            friend.setId(ObjectId.get());
            friend.setUserId(userId1);

            mongoTemplate.save(friend);
        }

        //2. 给userId2添加好友：userId1
        exists = mongoTemplate.exists(new Query(Criteria.where("userId").is(userId2).and("friendId").is(userId1)), Friend.class);
        if (!exists){
            Friend friend = new Friend();
            friend.setUserId(userId2);
            friend.setId(ObjectId.get());
            friend.setFriendId(userId1);
            friend.setCreated(System.currentTimeMillis());

            mongoTemplate.save(friend);
        }
    }

    /**
     * 查询好友列表
     * @param page 页码
     * @param pagesize 查询几条
     * @param keyword 搜索关键字
     * @param userId 用户id
     * @return
     */
    @Override
    public PageResult<Friend> findFriendList(int page, int pagesize, String keyword, long userId) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = new Query(criteria)
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page-1,pagesize));

        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        long count = mongoTemplate.count(query, Friend.class);
        int pages = (int) Math.ceil(count*1.0/pagesize);
        return new PageResult<>((int) count,pagesize,pages,page,friendList);
    }
}
